import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

class FormUtil {
  static Widget textField(
    String formKey,
    String value, {
    TextInputType keyboardType = TextInputType.text,
    FocusNode focusNode,
    controller: TextEditingController,
    onChanged: Function,
    String hintText,
    IconData prefixIcon,
    onClear: Function,
    bool obscureText = false,
    height = 50.0,
    margin = 10.0,
  }) {
    return Container(
      height: height,
      margin: EdgeInsets.all(margin),
      child: Column(
        children: [
          TextField(
              keyboardType: keyboardType,
              focusNode: focusNode,
              obscureText: obscureText,
              controller: controller,
              decoration: InputDecoration(
                hintText: hintText,
                icon: Icon(
                  prefixIcon,
                  size: 20.0,
                ),
                border: InputBorder.none,
                suffixIcon: GestureDetector(
                  child: Offstage(
                    child: Icon(Icons.clear),
                    offstage: value == null || value == '',
                  ),
                  onTap: () {
                    onClear(formKey);
                  },
                ),
              ),
              onChanged: (value) {
                onChanged(formKey, value);
              }),
          Divider(
            height: 1.0,
            color: Colors.grey[400],
          ),
        ],
      ),
    );
  }

  static Widget imagePicker(
    String formKey,
    Function onTapped, {
    File imageFile,
    String imageUrl,
    double width = 80.0,
    double height = 80.0,
  }) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.all(10),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.grey[300],
          border: Border.all(width: 0.5, style: BorderStyle.solid),
          borderRadius: BorderRadius.all(Radius.circular(4.0)),
        ),
        child: _getImageWidget(imageFile, imageUrl, width, height),
        width: width,
        height: height,
      ),
      onTap: onTapped,
    );
  }

  static Widget _getImageWidget(
      File imageFile, String imageUrl, double width, double height) {
    if (imageFile != null) {
      return Image.file(
        imageFile,
        fit: BoxFit.cover,
        width: width,
        height: height,
      );
    }
    if (imageUrl != null) {
      return CachedNetworkImage(
        imageUrl: imageUrl,
        fit: BoxFit.cover,
        width: width,
        height: height,
      );
    }

    return Icon(Icons.add_photo_alternate);
  }
}
